package com.googlecode.sere.method

import com.googlecode.sere.util.Logging
import com.googlecode.sere.translation.AcceptedTypes
import com.googlecode.sere.http.{Status, EnclosedEntity, HttpRequest}
import com.googlecode.sere.core.{UrlRegistry, InvocationData}

class PutMethod(uri: String, entity: EnclosedEntity)
  extends EntityEnclosingMethod(uri, entity, AcceptedTypes()) with Logging {

  def process(meta: InvocationData) = {
    val (resourceType, id) = UrlRegistry.matchUrl(uri)
    // Lazy value to avoid parsing when another error (such as a 404) will occur
    lazy val parserEntity = resourceType.parse(entity)
    resourceType.put(id, parserEntity, meta)
    EmptyResponse(Status.Ok)
  }
}

object PutMethod {
  def fromRequest(request: HttpRequest) = new PutMethod(request.uri,
    EntityEnclosingMethod.entityFromRequest(request))
}